package cn.tm.ms.nerver.filter.route;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import io.netty.buffer.ByteBuf;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import cn.tm.ms.nerver.common.utils.BeanUtils;
import cn.tm.ms.nerver.filter.route.entry.FilterREQ;
import cn.tm.ms.nerver.filter.route.entry.FilterRES;

public class GetRoute {

	public FilterRES route(FilterREQ req){
		final FilterRES res=new FilterRES();
		try {
			RxNetty.createHttpGet(req.getUri()).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() {
				public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> response) {
					res.setCookies(response.getCookies());
					Map<String,Object> headers=new HashMap<String, Object>();
					try {
						BeanUtils.copyProperties(response.getHeaders(), headers);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return response.getContent();
				}
			}).map(new Func1<ByteBuf, ByteBuf>() {
				public ByteBuf call(ByteBuf data) {
					return data;
				}
			}).toBlocking().forEach(new Action1<ByteBuf>() {
				public void call(ByteBuf data) {
					res.setData(data.copy().array());
				}
			});
			return res;
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		FilterREQ req=new FilterREQ();
		req.setUri("http://www.baidu.com");
		FilterRES res=new GetRoute().route(req);
		System.out.println(JSON.toJSONString(res));
		System.out.println("Client => " + new String(res.getData(), Charset.defaultCharset()));
	}
}
